package com.demo.utils;


import com.demo.config.AppConfig;
import com.demo.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Component("emailUtils")
public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private AppConfig appConfig;

    public void sendEmail4Warn(String email, String tips) {
        try {

            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //邮件发件人
            helper.setFrom(appConfig.getUserName());
            //邮件收件人 1或多个
            helper.setTo(email);
            //邮件主题
            helper.setSubject("预约消息推送");
            //邮件内容
            helper.setText(tips);
            //邮件发送时间
            helper.setSentDate(new Date());
            javaMailSender.send(message);
        } catch (Exception e) {
            logger.error("发送邮件失败=>{}", e);
            throw new BusinessException("邮箱发送失败");
        }
    }
}
